const { spawn } = require('child_process')
const fs = require('fs')
const { join } = require('path')

const consola = require('consola')
const fg = require('fast-glob')
// diff -r /Users/bytedance/Desktop/temp/folder-a /Users/bytedance/Desktop/temp/folder-b

// 替换成本地文件夹路径
const newDirRoot = '/Users/bytedance/Documents/APM/slardar_sdk-copy-third/packages'
const oldDirRoot = '/Users/bytedance/Documents/APM/slardar_sdk/packages'

const unionDirs = ['esm', 'cn', 'dist', 'india', 'maliva', 'oci', 'sg', 'private', 'build', 'bin']
const allPackages = fg
  .sync(`${oldDirRoot}/**`, {
    cwd: 'dir',
    deep: 1,
    onlyDirectories: true,
  })
  .map((path) => path.split('/').pop())

allPackages.forEach((p) => {
  const packagePath = join(oldDirRoot, p)
  unionDirs.forEach((production) => {
    const productionDir = join(packagePath, production)
    if (fs.existsSync(productionDir)) {
      const newProductionDir = join(newDirRoot, p, production)
      if (fs.existsSync(newProductionDir)) {
        diff(productionDir, join(newDirRoot, p, production))
      } else {
        consola.error(`new ${p}/${production} isn't exist`)
      }
    }
  })
})

function diff(path_1, path_2) {
  const diff = spawn('diff', ['-qr', path_1, path_2])
  consola.info('diff', path_1, path_2)
  diff.stdout.on('data', (data) => {
    consola.error(`errors: ${data}`)
  })
  const packageSplit = path_1.split('/')
  diff.on('close', (code) => {
    if (code === 1) {
      return consola.error(
        `${packageSplit[packageSplit.length - 2]}/${packageSplit[packageSplit.length - 1]} diff error`,
      )
    }
    consola.success(
      `${packageSplit[packageSplit.length - 2]}/${packageSplit[packageSplit.length - 1]} is exactly the same`,
    )
  })
}
